package com.applink.sell_proof;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.database.table.PriceBookDBHelper;
import com.applink.sell_proof.model.MyImage;
import com.applink.sell_proof.model.PriceBook;
import com.applink.sell_proof.urlimageviewhelper.GalleryViewPager;
import com.applink.sell_proof.urlimageviewhelper.UrlPagerAdapter;
import com.applink.sell_proof.util.Utility;

public class PriceBookActivity extends BaseActionBarActivity implements
		OnItemSelectedListener, Observer {
	static final int DATE_DIALOG_ID = 999;
	private static final int DISMISS_PROGRESS = 2;
	private static final int SHOW_PRICE_BOOK = 0;
	private static final int SHOW_PROGRESS = 1;
	private GalleryViewPager galleryPriceBook;
	private ImageView imgNoPriceBook;
	protected Context mContext;
	private ArrayList<PriceBook> mDataSelect = new ArrayList<PriceBook>();
	private ArrayList<PriceBook> mNewPriceBooks = new ArrayList<PriceBook>();
	private ArrayList<PriceBook> mLocalPriceBook = new ArrayList<PriceBook>();
	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			switch (arg0.what) {
			case SHOW_PRICE_BOOK:
				showPriceBook();
				break;

			case SHOW_PROGRESS:
				Utility.showWaitingStatus(processDialog);
				break;

			case DISMISS_PROGRESS:
				Utility.hideWaitingStatus(processDialog);
				break;
			default:
				break;
			}
			return false;
		}
	});
	private ArrayList<MyImage> mUrlPriceBook = new ArrayList<MyImage>();
	private ProgressDialog processDialog;

	private class DownloadPriceBook extends AsyncTask<Void, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected Integer doInBackground(Void... params) {
			mDataSelect.clear();
			if (mNewPriceBooks != null && mNewPriceBooks.size() > 0) {
				for (PriceBook priceBook : mNewPriceBooks) {
					if (priceBook.getPhysicalPathLocal() != null
							&& priceBook.getPhysicalPathLocal().length() == 0) {
						String url = Utility.download(priceBook
								.getPhysicalPath());
						if (url != null) {
							priceBook.setPhysicalPathLocal(url);
							PriceBookDBHelper.updatePriceBook(priceBook);
						}
					}
				}
			}
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			reloadPriceBook();
			hideloading();
		}
	}

	private void reloadPriceBook() {
		if (mDataSelect != null) {
			mDataSelect.clear();
		}
		if (mNewPriceBooks != null) {
			mNewPriceBooks.clear();
		}
		if (mLocalPriceBook != null) {
			mLocalPriceBook.clear();
		}
		mLocalPriceBook = PriceBookDBHelper.getAllPriceBook();
		if (mLocalPriceBook != null) {
			loadData(mLocalPriceBook);
			mHandler.sendEmptyMessage(SHOW_PRICE_BOOK);
		}
	}

	private void changeOptionSelect(String optionName) {
		mDataSelect.clear();
		if (mLocalPriceBook != null) {
			if (optionName.equals("All")) {
				mDataSelect.addAll(mLocalPriceBook);
			} else if (mLocalPriceBook.size() > 0) {
				for (int i = 0; i < mLocalPriceBook.size(); i++) {
					if (optionName.equals(mLocalPriceBook.get(i)
							.getSaleCategoryName().toLowerCase())) {
						mDataSelect.add(mLocalPriceBook.get(i));
					}
				}
			}
		}

	}

	private void getLeatestPromotion() {
		PriceBookDBHelper.deleteAllPricebook();
		showloading();
		Utility.checkGetLastestPriceBook = true;
		DataHelper.getInstance().getPriceBook();
	}

	private void initView() {
		DataHelper.getInstance().addObserver(this);
		Spinner spin = (Spinner) findViewById(R.id.spinnerPriceBook);
		spin.setOnItemSelectedListener(this);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.price_book, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adapter);

		if (galleryPriceBook == null) {
			galleryPriceBook = (GalleryViewPager) findViewById(R.id.gallery_price_book);
		}

		if (imgNoPriceBook == null) {
			imgNoPriceBook = (ImageView) findViewById(R.id.img_no_photo_price_book);
		}

		reloadPriceBook();
	}

	private void loadData(ArrayList<PriceBook> data) {
		mUrlPriceBook.clear();
		if (data != null && data.size() > 0) {
			for (int i = 0; i < data.size(); i++) {
				MyImage objectPDFImage = new MyImage();
				if (data.get(i).getPhysicalPathLocal() != null
						&& data.get(i).getPhysicalPathLocal().length() > 0) {
					objectPDFImage.setImageLocation(Uri.parse(data.get(i)
							.getPhysicalPathLocal()));
				}
				mUrlPriceBook.add(i, objectPDFImage);
			}
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.price_book);
		mContext = this;
		processDialog = new ProgressDialog(this);
		initView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.get_last_pricebook, menu);
		return true;
	}

	@Override
	public void onItemSelected(AdapterView<?> parentView,
			View selectedItemView, int position, long id) {
		if (position == 0) {
			changeOptionSelect("All");
		} else if (position == 1) {
			changeOptionSelect("desktop");
		} else if (position == 2) {
			changeOptionSelect("notebook");
		} else if (position == 3) {
			changeOptionSelect("workstation");
		}
		loadData(mDataSelect);
		mHandler.sendEmptyMessage(SHOW_PRICE_BOOK);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parentView) {

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_get_lastest_pricebook:
			getLeatestPromotion();
			break;

		default:
			break;
		}
		return false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		int checkState = Utility.checkTimeValidation();
		if (mLocalPriceBook != null) {
			mHandler.sendEmptyMessage(SHOW_PRICE_BOOK);
		}
		switch (checkState) {
		case 0:
			Utility.showAlertDialogLogout(this,
					android.R.drawable.ic_dialog_alert,
					Utility.messageServerTimeOut, Utility.titleServerTimeOut,
					PriceBookActivity.this);
			break;
		case 1:
			Utility.showAlertDialogLogout(this,
					android.R.drawable.ic_dialog_alert,
					Utility.messageLocalTimeOut, Utility.titleLocalTimeOut,
					PriceBookActivity.this);
			break;

		default:
			break;
		}
	}

	private void showPriceBook() {
		if (mUrlPriceBook.size() > 0) {
			imgNoPriceBook.setVisibility(View.GONE);
			galleryPriceBook.setVisibility(View.VISIBLE);
			UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(mContext,
					mUrlPriceBook);
			galleryPriceBook.setAdapter(pagerAdapter);
		} else {
			imgNoPriceBook.setVisibility(View.VISIBLE);
			galleryPriceBook.setVisibility(View.GONE);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		DataResult result = (DataResult) data;
		if (result.getMethodName().equals(Methods.getPriceBook)) {
			mNewPriceBooks = (ArrayList<PriceBook>) result.getData();
			if (mNewPriceBooks.size() > 0) {
				DownloadPriceBook priceBook = new DownloadPriceBook();
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
					priceBook.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
							(Void) null);
				} else {
					priceBook.execute();
				}
			} else {
				hideloading();
				Utility.showAlertDialog(mContext,
						android.R.drawable.ic_dialog_info,
						"you already have the latest pricebooks", "Notice");
			}
		}
	}

}
